/**
 * 性能监控工具
 * 用于监控API请求性能和缓存效果
 */

interface PerformanceMetric {
  name: string;
  startTime: number;
  endTime?: number;
  duration?: number;
  metadata?: any;
}

interface ApiRequestMetric {
  url: string;
  method: string;
  startTime: number;
  endTime?: number;
  duration?: number;
  fromCache: boolean;
  success: boolean;
  error?: string;
}

class PerformanceMonitor {
  private metrics: PerformanceMetric[] = [];
  private apiMetrics: ApiRequestMetric[] = [];
  private readonly MAX_METRICS = 100; // 最大保存的指标数量

  /**
   * 开始性能测量
   */
  startMeasure(name: string, metadata?: any): string {
    const id = `${name}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    this.metrics.push({
      name: id,
      startTime: performance.now(),
      metadata
    });

    return id;
  }

  /**
   * 结束性能测量
   */
  endMeasure(id: string): number | null {
    const metric = this.metrics.find(m => m.name === id);
    if (!metric) {
      console.warn(`Performance metric not found: ${id}`);
      return null;
    }

    metric.endTime = performance.now();
    metric.duration = metric.endTime - metric.startTime;

    // 清理过多的指标
    this.cleanupMetrics();

    return metric.duration;
  }

  /**
   * 记录API请求性能
   */
  recordApiRequest(config: {
    url: string;
    method: string;
    fromCache: boolean;
    success: boolean;
    duration: number;
    error?: string;
  }): void {
    this.apiMetrics.push({
      url: config.url,
      method: config.method,
      startTime: Date.now(),
      endTime: Date.now(),
      duration: config.duration,
      fromCache: config.fromCache,
      success: config.success,
      error: config.error
    });

    // 清理过多的API指标
    if (this.apiMetrics.length > this.MAX_METRICS) {
      this.apiMetrics = this.apiMetrics.slice(-this.MAX_METRICS);
    }
  }

  /**
   * 获取性能统计
   */
  getPerformanceStats() {
    const completedMetrics = this.metrics.filter(m => m.duration !== undefined);
    
    if (completedMetrics.length === 0) {
      return {
        count: 0,
        averageDuration: 0,
        minDuration: 0,
        maxDuration: 0
      };
    }

    const durations = completedMetrics.map(m => m.duration!);
    
    return {
      count: completedMetrics.length,
      averageDuration: durations.reduce((a, b) => a + b, 0) / durations.length,
      minDuration: Math.min(...durations),
      maxDuration: Math.max(...durations)
    };
  }

  /**
   * 获取API请求统计
   */
  getApiStats() {
    const totalRequests = this.apiMetrics.length;
    const cacheHits = this.apiMetrics.filter(m => m.fromCache).length;
    const successfulRequests = this.apiMetrics.filter(m => m.success).length;
    const failedRequests = totalRequests - successfulRequests;

    const durations = this.apiMetrics
      .filter(m => m.duration !== undefined)
      .map(m => m.duration!);

    const averageDuration = durations.length > 0 
      ? durations.reduce((a, b) => a + b, 0) / durations.length 
      : 0;

    return {
      totalRequests,
      cacheHits,
      cacheHitRate: totalRequests > 0 ? (cacheHits / totalRequests) * 100 : 0,
      successfulRequests,
      failedRequests,
      successRate: totalRequests > 0 ? (successfulRequests / totalRequests) * 100 : 0,
      averageDuration,
      averageNetworkDuration: this.getAverageNetworkDuration()
    };
  }

  /**
   * 获取最近的API请求
   */
  getRecentApiRequests(limit: number = 10): ApiRequestMetric[] {
    return this.apiMetrics.slice(-limit);
  }

  /**
   * 清理过期的性能指标
   */
  private cleanupMetrics(): void {
    if (this.metrics.length > this.MAX_METRICS) {
      this.metrics = this.metrics.slice(-this.MAX_METRICS);
    }
  }

  /**
   * 获取平均网络请求时间（排除缓存）
   */
  private getAverageNetworkDuration(): number {
    const networkRequests = this.apiMetrics.filter(m => !m.fromCache && m.duration !== undefined);
    
    if (networkRequests.length === 0) return 0;
    
    const durations = networkRequests.map(m => m.duration!);
    return durations.reduce((a, b) => a + b, 0) / durations.length;
  }

  /**
   * 导出性能报告
   */
  exportReport(): string {
    const performanceStats = this.getPerformanceStats();
    const apiStats = this.getApiStats();
    const recentRequests = this.getRecentApiRequests(5);

    const report = {
      timestamp: new Date().toISOString(),
      performance: performanceStats,
      api: apiStats,
      recentRequests: recentRequests.map(req => ({
        url: req.url,
        method: req.method,
        duration: req.duration,
        fromCache: req.fromCache,
        success: req.success,
        error: req.error
      }))
    };

    return JSON.stringify(report, null, 2);
  }

  /**
   * 清空所有指标
   */
  clear(): void {
    this.metrics = [];
    this.apiMetrics = [];
  }

  /**
   * 在控制台打印性能报告
   */
  logReport(): void {
    console.group('🚀 性能监控报告');
    
    const apiStats = this.getApiStats();
    console.log('📊 API请求统计:');
    console.table({
      '总请求数': apiStats.totalRequests,
      '缓存命中数': apiStats.cacheHits,
      '缓存命中率': `${apiStats.cacheHitRate.toFixed(1)}%`,
      '成功率': `${apiStats.successRate.toFixed(1)}%`,
      '平均响应时间': `${apiStats.averageDuration.toFixed(1)}ms`,
      '平均网络时间': `${apiStats.averageNetworkDuration.toFixed(1)}ms`
    });

    const performanceStats = this.getPerformanceStats();
    console.log('⏱️ 性能指标:');
    console.table({
      '测量次数': performanceStats.count,
      '平均耗时': `${performanceStats.averageDuration.toFixed(1)}ms`,
      '最短耗时': `${performanceStats.minDuration.toFixed(1)}ms`,
      '最长耗时': `${performanceStats.maxDuration.toFixed(1)}ms`
    });

    console.log('📋 最近请求:');
    console.table(this.getRecentApiRequests(5));
    
    console.groupEnd();
  }
}

// 创建全局性能监控实例
export const performanceMonitor = new PerformanceMonitor();

// 在开发环境下暴露到全局对象，方便调试
if (import.meta.env.DEV) {
  (window as any).performanceMonitor = performanceMonitor;
}

export default PerformanceMonitor;
